package org.opens.configure;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Configuration
public class GuavaCacheConfig {

    @Autowired
    private Cache guavaCache;

    @Bean(value = "guavaCache")
    public  Cache<String, Object> getCache() {
        Cache<String, Object> cache = CacheBuilder.newBuilder()
                .maximumSize(512)
                .expireAfterAccess(60, TimeUnit.SECONDS)
                .build();
        return cache;
    }

    public static <T> List<T> cacheObjectTransform(Object obj, Class<T> clazz) {
        List<T> result = new ArrayList<>();
        if(obj instanceof List<?>) {
            for(Object temp : (List<?>) obj) {
                //cast函数会进行转换
                result.add(clazz.cast(temp));
            }
        }
        return result;
    }

}
